/*
 * Copyright (c) 2010 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package com.sun.spot.wot;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import com.sun.spot.wot.http.HttpRequest;
import com.sun.spot.wot.http.HttpResponse;
import java.net.InetSocketAddress;

/**
 *
 * @author vgupta
 */
public class TCPHandler extends Thread {
    NanoAppServer nas = null;
    int port = 0;
    ServerSocket ss = null;

    public TCPHandler(int port, NanoAppServer nas) throws IOException {
        this.port = port;
        this.nas = nas;
        ss = new ServerSocket(port);
    }

    public void run() {
        boolean done = false;
        HttpRequest req = null;
        HttpResponse res = null;
        System.out.println("Starting TCP handler on port " + port + "...");

        while (!done) {
            try {
                new SocketHandler((Socket) ss.accept(), nas).start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Shutting down TCP handler on port " + port);

        try {
            ss.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

class SocketHandler extends Thread {
    private static int MAX_HEADER_SIZE = 1024;

    Socket sock = null;
    NanoAppServer nas = null;

    public SocketHandler(Socket sock, NanoAppServer nas) {
        this.sock = sock;
        this.nas = nas;
    }

    public void run() {
        InputStream is = null;
        OutputStream os = null;
        byte[] writeBuf = null;
        int i = 0;
        boolean done = false;
        Date d = new Date();

        try {
            d.setTime(System.currentTimeMillis());
//            System.out.println(d.toString() + ": Received TCP connection from " +
//                    sock.getInetAddress().getHostAddress());
            is = sock.getInputStream();
            os = sock.getOutputStream();

            while (!done) {
                HttpRequest req = new HttpRequest();
                HttpResponse res = new HttpResponse();

                try {
                    d.setTime(System.currentTimeMillis());
                    req.parse(is);
                    d.setTime(System.currentTimeMillis());
                    System.out.println(d.toString() + ": Received " +
                            req.getMethod() + " " + req.getPathInfo() +
                            ((req.getQueryString() == null) ?
                                "":
                                "?"+req.getQueryString()) + " over TCP from " +
                            ((InetSocketAddress) sock.getRemoteSocketAddress()).getAddress().getHostAddress() +
                            ", port " + sock.getPort());
                } catch (Exception ex) {
                    // If there is a problem reading the request, return BAD_INPUT
                    System.out.println("Caught " + ex);
                    req = null;
                    done = true;
                    res.setStatus(HttpResponse.SC_BAD_REQUEST);
                }

                if (req != null) {
                    res = nas.getResponse(req);

                    String connHdr = req.getHeader("Connection");
                    if (true || // Always force connection close
                            ((connHdr != null) &&
                            connHdr.equalsIgnoreCase("close"))) {
                        done = true;
                        res.setHeader("Connection", "close");
                    }
                }

                writeBuf = new byte[((res.getBody() == null) ? 0:res.getBody().length) +
                        MAX_HEADER_SIZE];
                int wlen = res.toByteArray((req == null) ?
                    false : req.isCompressed(),
                    writeBuf, 0);
                
                d.setTime(System.currentTimeMillis());
                System.out.println(d.toString() + ": Sent code " +
                        res.getStatus() + " over TCP to " +
                        sock.getRemoteSocketAddress());
                os.write(writeBuf, 0, wlen);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sock != null) {
                try {
//                    System.out.println("Closing TCP connection from " +
//                            sock.getInetAddress().toString());
                    sock.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
